<template>
  <view class="container">
    <PageHeader title='修改登录密码' :showBack="true" />
    <!-- 表单区域 -->
    <view class="form-container p-[28rpx] bg-white rounded-24rpx shadow-lg mt-6">
      <nut-form :model="formData" ref="formRef" :rules="rules">
        <!-- 当前密码 -->
        <view class="mb-6">
          <!-- 使用flex布局实现左文字+输入框+右图标在同一行 -->
          <view class="relative flex items-center">
            <!-- 左侧文字 -->
            <text class="text-[28rpx] text-gray-800 w-[160rpx]">旧密码</text>

            <!-- 中间输入框（自适应宽度） -->
            <nut-input v-model="formData.oldPassword" :type="oldPasswordVisible ? 'text' : 'password'"
              placeholder="请输入旧密码" placeholder-class="text-gray-400"
              class="flex-1 h-[88rpx] px-4 border border-gray-200 rounded-16rpx text-[28rpx]" name="oldPassword"
              @blur="validateField('oldPassword')" />

            <!-- 右侧图标（向左移动调整） -->
            <IconFont font-class-name="iconfont" class-prefix="icon"
              :name="oldPasswordVisible ? 'eye-open' : 'eye-close'" :key="oldPasswordVisible" size="32"
              class="text-gray-400 ml-[8rpx] mr-[30rpx]" @click="togglePasswordVisibility('oldPassword')" />
          </view>
          <!-- 手动错误提示 -->
          <text v-if="errors.oldPassword" class="text-red-500 text-[24rpx] mt-2 block pl-[160rpx]">{{ errors.oldPassword
          }}</text>
        </view>

        <!-- 新密码 -->
        <view class="mb-6">
          <view class="relative flex items-center">
            <text class="text-[26rpx] text-gray-800 w-[160rpx]">新密码</text>
            <nut-input v-model="formData.newPassword" :type="newPasswordVisible ? 'text' : 'password'"
              placeholder="请设置新密码（至少6位）" placeholder-class="text-gray-400"
              class="flex-1 h-[88rpx] px-4 border border-gray-200 rounded-16rpx text-[28rpx]" name="newPassword"
              @blur="validateField('newPassword')" />
            <IconFont font-class-name="iconfont" class-prefix="icon"
              :name="newPasswordVisible ? 'eye-open' : 'eye-close'" :key="newPasswordVisible" size="32"
              class="text-gray-400 ml-[8rpx] mr-[30rpx]" @click="togglePasswordVisibility('newPassword')" />
          </view>
          <!-- 手动错误提示 -->
          <text v-if="errors.newPassword" class="text-red-500 text-[24rpx] mt-2 block pl-[160rpx]">{{ errors.newPassword
          }}</text>
        </view>

        <!-- 确认新密码 -->
        <view class="mb-8">
          <view class="relative flex items-center">
            <text class="text-[26rpx] text-gray-800 w-[160rpx]">确认密码</text>
            <nut-input v-model="formData.confirmPassword" :type="confirmPasswordVisible ? 'text' : 'password'"
              placeholder="请再次输入新密码" placeholder-class="text-gray-400"
              class="flex-1 h-[88rpx] px-4 border border-gray-200 rounded-16rpx text-[28rpx]" name="confirmPassword"
              @blur="validateField('confirmPassword')" />
            <IconFont font-class-name="iconfont" class-prefix="icon"
              :name="confirmPasswordVisible ? 'eye-open' : 'eye-close'" :key="confirmPasswordVisible" size="32"
              class="text-gray-400 ml-[4rpx] mr-[30rpx]" @click="togglePasswordVisibility('confirmPassword')" />
          </view>
          <!-- 手动错误提示 -->
          <text v-if="errors.confirmPassword" class="text-red-500 text-[24rpx] mt-2 block pl-[160rpx]">{{
            errors.confirmPassword }}</text>
        </view>

        <!-- 提交按钮 -->
        <nut-button type="primary" size="large" :loading="submitting" @click="submitForm"
          class="w-full h-[88rpx] rounded-[44rpx] text-[32rpx] bg-green-500">
          确认修改
        </nut-button>
      </nut-form>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import Taro, { showToast } from '@tarojs/taro'
import { Form, Input, Button } from '@nutui/nutui-taro'  // 移除 FormError 导入
import { IconFont } from '@nutui/icons-vue-taro'
import { post } from '@/utils/request'
import { View } from '@tarojs/components'
import PageHeader from '@/components/PageHeader.vue'

// 表单数据
const formData = reactive({
  // oldPassword: '111111',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 错误信息存储
const errors = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码可见性
const oldPasswordVisible = ref(false)
const newPasswordVisible = ref(false)
const confirmPasswordVisible = ref(false)

// 提交状态
const submitting = ref(false)
const formRef = ref(null)

// 表单校验规则
const rules = {
  oldPassword: [
    { required: true, message: '请输入当前密码' }
  ],
  newPassword: [
    { required: true, message: '请设置新密码' },
    { min: 6, message: '新密码不能少于6位' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码' },
    {
      validator: (rule, value) => {
        return value === formData.newPassword || '两次输入的密码不一致'
      }
    }
  ]
}

// 验证单个字段
const validateField = (field) => {
  const ruleList = rules[field]
  if (!ruleList) return true

  for (const rule of ruleList) {
    // 必填验证
    if (rule.required && !formData[field]) {
      errors[field] = rule.message
      return false
    }
    // 长度验证
    if (rule.min && formData[field].length < rule.min) {
      errors[field] = rule.message
      return false
    }
    // 自定义验证器
    if (rule.validator) {
      const result = rule.validator(rule, formData[field])
      if (result !== true) {
        errors[field] = result
        return false
      }
    }
  }

  // 验证通过清空错误
  errors[field] = ''
  return true
}

// 整体表单验证
const validateForm = () => {
  let isValid = true
  Object.keys(rules).forEach(field => {
    if (!validateField(field)) {
      isValid = false
    }
  })
  return isValid
}

// 返回上一页
const goBack = () => {
  Taro.navigateBack({
    delta: 1,
  });
};

// 获取路由上的参数
// const urlId = Taro.getCurrentInstance().router?.params?.id
// console.log(urlId)

// 切换密码可见性
const togglePasswordVisibility = (type) => {
  switch (type) {
    case 'oldPassword':
      console.log(`切换前：${type}=${oldPasswordVisible.value}`);
      oldPasswordVisible.value = !oldPasswordVisible.value
      console.log(`切换后：${type}=${oldPasswordVisible.value}`);
      break
    case 'newPassword':
      newPasswordVisible.value = !newPasswordVisible.value
      break
    case 'confirmPassword':
      confirmPasswordVisible.value = !confirmPasswordVisible.value
      break
  }
}

// 提交表单
const submitForm = async () => {
  // 整体验证表单
  if (!validateForm()) {
    return
  }

  submitting.value = true

  try {
    // 修改密码
    const res = await post('/user/updateLoginPassword', {
      oldPassword: formData.oldPassword,
      password: formData.newPassword
    })

    console.log(res)
    if (res.code === 0) {
      showToast({
        title: '密码修改成功',
        icon: 'success'
      })

      // 延迟后返回上一页
      setTimeout(() => {
        Taro.navigateBack({
          delta: 1,
        })
      }, 1500)
    } else {
      showToast({
        title: res.message || '修改失败，请重试',
        icon: 'none'
      })
    }

  } catch (error) {
    console.error('修改密码失败:', error)
    showToast({
      title: '修改密码失败，请重试',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}
</script>

<style lang="scss">
/* 样式保持不变 */
.container {
  width: 750rpx;
  min-height: 100vh;
  background-color: #f7f8fa;
}

.shadow-lg {
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.rounded-16rpx {
  border-radius: 16rpx;
}

.rounded-24rpx {
  border-radius: 24rpx;
}

.mt-6 {
  margin-top: 24rpx;
}

.mb-6 {
  margin-bottom: 24rpx;
}

.mb-8 {
  margin-bottom: 32rpx;
}

.border-gray-200 {
  border-color: #EBEEF5;
}

.text-red-500 {
  color: #F56C6C;
}
</style>